{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\l\\Anaconda3\\lib\\site-packages\\h5py\\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "from PIL import Image, ImageDraw, ImageFont\n",
    "import cv2\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = open('./labels.txt',encoding='utf-8')\n",
    "\n",
    "label_dict = {}\n",
    "for item in f.readlines():\n",
    "    item = item.strip().split(':') \n",
    "    label_dict[int(item[0])] = {'id':int(item[0]),'name':item[1]}\n",
    "\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "{0: {'id': 0, 'name': 'Jeep-北京JEEP'}, 1: {'id': 1, 'name': 'Jeep-大切诺基'}, 2: {'id': 2, 'name': 'Jeep-大切诺基SRT'}, 3: {'id': 3, 'name': 'Jeep-指南者'}, 4: {'id': 4, 'name': 'Jeep-牧马人'},"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load image into numpy array\n",
    "def load_image_into_numpy_array(image):\n",
    "    (im_width, im_height) = image.size\n",
    "    return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8), im_height, im_width"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "320\n",
      "432\n"
     ]
    }
   ],
   "source": [
    "# load image into numpy array\n",
    "image = Image.open('./test1.jpg')\n",
    "(image_np, im_height, im_width) = load_image_into_numpy_array(image)\n",
    "print(im_height)\n",
    "print(im_width)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "650\n",
      "1200\n"
     ]
    }
   ],
   "source": [
    "# load image into numpy array\n",
    "image = Image.open('./test2.jpg')\n",
    "(image_np, im_height, im_width) = load_image_into_numpy_array(image)\n",
    "print(im_height)\n",
    "print(im_width)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# x1\n",
    "x1 = int(0.21775927*432)\n",
    "# y1\n",
    "y1 = int(0.6717261*320)\n",
    "# x2\n",
    "x2 = int(0.46072263*432)\n",
    "# y2\n",
    "y2 = int(0.94666123*320)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# define the crop op\n",
    "image_crop = tf.image.crop_to_bounding_box(\n",
    "        image_np, \n",
    "        offset_height=y1, offset_width=x1, \n",
    "        target_height=y2-y1, target_width=x2-x1)\n",
    "\n",
    "img_crop = Image.fromarray(tf.Session().run(image_crop), 'RGB')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "# save crop part to file\n",
    "img_crop.save('crop.jpg')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'本田-竞瑞'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 349: class index\n",
    "label_dict[434]['name']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# get the referred classname\n",
    "car_name = label_dict[434]['name']\n",
    "len_background = len(car_name.encode('gb2312'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "# read the primary image and initialize the drawing\n",
    "im = cv2.imread('./test1.jpg', cv2.COLOR_BGR2RGB)\n",
    "pil_im = Image.fromarray(im)\n",
    "draw = ImageDraw.Draw(pil_im)\n",
    "font = ImageFont.truetype('./simhei.ttf', 18, encoding='utf-8')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "# plot the text background\n",
    "draw.rectangle((x1, y1, x1 + len_background*9, y1+18), \n",
    "               fill=(211, 211, 211), outline=None)\n",
    "# write classname on the image\n",
    "draw.text((x1, y1), car_name, (255, 0, 255), font=font)\n",
    "# plot the bounding box\n",
    "draw.line((261, 436, 552, 436), (0, 255, 0), width=3)\n",
    "draw.line((552, 436, 552, 615), (0, 255, 0), width=3)\n",
    "draw.line((552, 615, 261, 615), (0, 255, 0), width=3)\n",
    "draw.line((261, 615, 261, 436), (0, 255, 0), width=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# save to out1.jpg\n",
    "im = np.array(pil_im)\n",
    "cv2.imwrite('./out1.jpg', im)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
